import { useEffect, useState } from 'react'

export function useLocalStorage(key) {
  // useState中的函数会立即执行
  const [data, setData] = useState(() => {
    const item = localStorage.getItem(key)
    if (!item) return ''
    return JSON.parse(item)
  })

  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(data))
  }, [data, key])

  return [data, setData]
}
